<?php

//SELECT MONTH(date_created), YEAR(date_created), COUNT(*)
//
//FROM contact_requests 
//
//GROUP BY MONTH(date_created), YEAR(date_created)
include 'connect/connect.php';
require_once 'sympols.php';
include 'lib/json_decoder.php';
error_reporting(E_ALL);

function arrayToParams(array $arr) {
    $res = "";
    foreach ($arr as $key => $val) {
        $res.="$key=$val&";
    }
    return $res;
}

function getCode($appId) {
    $query = "SELECT app_url FROM apps where id='$appId'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    $row = mysql_fetch_assoc($result);
    extract($row);
    return "$appId" . Sympols::$split1 . jsonToWare(file_get_contents($app_url . "?" . arrayToParams($_GET)));
}

function applicationAccessed($appId, $userId) {
    $query = "INSERT INTO app_usage SET app_id='$appId', user_id='$userId'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
}

/*
 * variable called state which takes 3 possible states
 * 1. initial: Means its the first time the application has connected
 * 2. submit: Means somedata has been submitted e.g form data
 * 3. select: Means some option has been selected e.g form button other than submit or list item clicked
 * then above are exposed to 3rd part apps in addition to the payment status defined below
 * 4. list_apps: Means list all avaialble applications
 * 5. register: means register a new users, only if the phone number does not already exist
 * 6. login: validate a user with their phone number and password
 * 7. home: the first screen after login/register: show the catgories of apps i.e favourite, popular, new, all.
 * 8. payment: this is when the mpesa server receives money, it updatesthe server
 * 9.
 */


/* Payments statuses sent to 3rd party apps
 * paid_success: when we found the trans code and the status was 'pending'
 * paid_used: when we found the trans code and the status was 'used'
 * paid_pending: when we did not find the trans code (probably the users entered a wrong trans code)
 */
$state = $_GET['state'];
$systemName = "main";
$categories = array("fav" => "Favourite", "new" => "New", "pop" => "Most popular", "all" => "All");
if ($state == "register") {
    extract($_GET);
    $query = "SELECT * FROM users WHERE phone_number='$phone_number'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    if (mysql_num_rows($result) > 0) {
        echo "Failed: That phone number already exists.";
    } else {
        $query = "INSERT INTO users SET phone_number='$phone_number',password='$password'";
        $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
        echo "success";
    }
} else if ($state == "login") {
    extract($_GET);
    $query = "SELECT * FROM users WHERE phone_number='$phone_number' and password='$password'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    if (mysql_num_rows($result) > 0) {
        echo "success";
    } else {
        echo "Failed: Wrong password.";
    }
} else if ($state == "home") {
    $paint_str = "{list:{list_id:'WC',title:'Welcome to Ware',items: [";
    foreach ($categories as $id => $name) {
        $paint_str.="{id:'$id', label:'$name'},";
    }
    $paint_str = substr($paint_str, 0, strlen($paint_str) - 1) . "]}}";
    echo "categories" . Sympols::$split1 . jsonToWare($paint_str);
} else if ($state == "payment") {// when a new payments hits the mpesa server, it updates our online server
    extract($_GET);
    $query = "INSERT INTO payments SET code='$code',amount='$amount',phoneNo='$phoneNo',names='$names'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    echo "success";
} else if (isset($_GET['transCode'])) {//when the users enters the transaction code and submits it, we validate it and forward the result to the third party applications.
    extract($_GET);
    $query = "SELECT * FROM payments where code='$transCode'";
    $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    $status = "";
    if (mysql_num_rows($result) > 0) {
        $row = mysql_fetch_assoc($result);
        if ($row['status'] == "unused") {
            $status = "paid_success";
            $_GET['names'] = $row['names'];
            $_GET['code'] = $row['code'];
            $_GET['amount'] = $row['amount'];
            $_GET['phoneNo'] = $row['phoneNo'];
            $query = "UPDATE payments set status='used' where code='$transCode'";
            mysql_query($query) or die("Error executing '$query':" . mysql_error());
        } else {
            $status = "paid_used";
        }
    } else {
        $status = "paid_pending";
    }

    $appId = $_GET['appId'];
    $query = "SELECT app_url FROM apps where id='$appId' ";
    $queryResult = mysql_query($query) or die("Error executing '$query':" . mysql_error());
    $row = mysql_fetch_assoc($queryResult);
    extract($row);

    $_GET['state'] = $status;
    echo "$appId" . Sympols::$split1 . "" . jsonToWare(file_get_contents($app_url . "?" . arrayToParams($_GET)));
} else {
    $appId = $_GET['appId'];
    if ($appId == "categories") {
        $sid = $_GET['sid'];
        if ($sid == 'new') {
            $query = "SELECT * FROM apps ORDER BY date_added desc";
        } else if ($sid == 'fav') {
            $phone_number = $_GET['phone_number'];
            $query = "SELECT ap.app_name, us.app_id as 'id', COUNT( * ) TotalCount
                        FROM app_usage us, apps ap
                        WHERE ap.id = us.app_id
                        AND us.user_id =  '$phone_number'
                        GROUP BY us.app_id
                        HAVING COUNT( * ) >0
                        ORDER BY COUNT( * ) DESC";
        } else if ($sid == 'pop') {
            $query = "SELECT ap.app_name ,us.app_id as 'id', COUNT(*) TotalCount
                        FROM app_usage us, apps ap 
                        WHERE ap.id=us.app_id
                        GROUP BY us.app_id
                        HAVING COUNT(*) > 0
                        ORDER BY COUNT(*) DESC";
        } else if ($sid == 'all') {
            $query = "SELECT * FROM apps ORDER BY app_name asc";
        } else {
            echo $systemName . "" . Sympols::$split1 . "form" . Sympols::$split1 . "Invalid category" . Sympols::$split1 . "Err" . Sympols::$split1 . "label" . Sympols::$split3 . "Sorry, no '$sid' category.";
            exit;
        }
        $result = mysql_query($query) or die("Error executing '$query':" . mysql_error());
        if (mysql_num_rows($result) > 0) {
            $paint_str = "list_apps" . Sympols::$split1 . "list" . Sympols::$split1 . "" . $categories[$_GET['sid']] . "" . Sympols::$split1 . "cat_listid" . Sympols::$split1 . "";
            while ($row = mysql_fetch_assoc($result)) {
                extract($row);
                $paint_str.="$id" . Sympols::$split3 . "$app_name" . Sympols::$split2;
            }
            echo $paint_str;
        } else {
            echo $systemName . "" . Sympols::$split1 . "form" . Sympols::$split1 . "No available apps" . Sympols::$split1 . "Err1" . Sympols::$split1 . "label" . Sympols::$split3 . "Sorry, there are no applications available.";
        }
    } else if ($appId == "list_apps") {
        $appId = $_GET['sid'];
        $userId = $_GET['phone_number'];
        $_GET['state'] = "initial";
        applicationAccessed($appId, $userId);
        echo getCode($appId);
    } else {//emulator start here
        echo getCode($appId);
    }
}
?>